package cn.itcast.bos.action.take_delivery;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.action.base.BaseAction;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {
	
	private static final Logger logger = Logger.getLogger(WayBillAction.class);
	
	@Autowired
	private WayBillService wayBillService;
	
	@Action(value="saveWayBill",results={@Result(name="success",type="json")})
	public String saveWayBill(){
		HashMap<String,Object> map = new HashMap<String, Object>();
		try {
			wayBillService.saveWayBill(model);
			map.put("success", true);
			map.put("msg", "保存成功");
		logger.info("保存运单成功！运单号:"+model.getWayBillNum());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "保存失败");
			logger.error("运单保存失败！运单号:"+model.getWayBillNum(),e);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	@Action(value="queryPageWayBill",results={@Result(name="success",type="json")})
	public String queryPageWayBill(){
		
		Pageable pageAble = new PageRequest(page-1, rows,new Sort(Direction.DESC, "id"));
		
		Page<WayBill> page = wayBillService.queryPageWayBill(pageAble);
		
		pushPageDataToValueStack(page);
		
		return SUCCESS;
	}
	
	@Action(value="findWayBillByWayBillNum",results={@Result(name="success",type="json")})
	public String findWayBillByWayBillNum(){
		Map<String, Object> map = new HashMap<String, Object>();
		WayBill wayBill = wayBillService.findWayBillByWayBillNum(model.getWayBillNum());
		if (wayBill!=null) {
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}else{
			map.put("success", false);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
}
